﻿using CsvHelper;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace LeakView.common
{

    public class NetTools
    {
        public static TcpClient BuildTcpClient(string host, int port, int connectTimeout)
        {
            TcpClient client = new TcpClient();

            IAsyncResult connResult = client.BeginConnect(host, port, null, null);
            connResult.AsyncWaitHandle.WaitOne(Math.Max(connectTimeout, 2000), true);
            if (!connResult.IsCompleted)
            {
                client.Close();
                client.Dispose();
                return null;
            }
            else
            {
                return client;
            }
        }
    }

    public class Tools
    {


        // DateTime --> long
        public static long ConvertDataTimeToLong(DateTime dt)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            TimeSpan toNow = dt.Subtract(dtStart);
            long timeStamp = toNow.Ticks;
            timeStamp = long.Parse(timeStamp.ToString().Substring(0, timeStamp.ToString().Length - 4));
            return timeStamp;
        }


        // long --> DateTime
        public static DateTime ConvertLongToDateTime(long d)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(d + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }

        public static string ConvertUnicodeToSystem(string unicodeString)
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            Encoding gb2312 = Encoding.GetEncoding("gb2312");
            Byte[] encodedBytes = utf8.GetBytes(unicodeString);
            String decodedString = gb2312.GetString(encodedBytes);
            return decodedString;
        }

    }

    public class CSharpUtilities
    {

        public static bool IsDesignMode()
        {
            bool returnFlag = false;

#if DEBUG
            if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
            {
                returnFlag = true;
            }
            else if (Process.GetCurrentProcess().ProcessName == "devenv")
            {
                returnFlag = true;
            }
#endif

            return returnFlag;
        }

    }

    public class ExportCSV
    {
        private static SaveFileDialog saveFileDialog = null;

        public static SaveFileDialog SaveDialog
        {
            get
            {
                if(saveFileDialog == null)
                {
                    saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
                    saveFileDialog.DefaultExt = "csv";
                    saveFileDialog.Title = "选择保存文件";
                }
                return saveFileDialog;
            }
        }

        public static void export(DataGridView dgv)
        {
            if (dgv.Rows.Count == 0)
            {
                MessageBox.Show("没有可以导出的数据！");
                return;
            }

            var result = SaveDialog.ShowDialog();
            if (result != DialogResult.OK)
            {
                return;
            }

            using (var writer = new StreamWriter(saveFileDialog.FileName, false, Encoding.GetEncoding(936)))
            using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                foreach (DataGridViewColumn column in dgv.Columns)
                {
                    csv.WriteField(column.HeaderText);
                }
                csv.NextRecord();

                foreach (DataGridViewRow row in dgv.Rows)
                {
                    for (var i = 0; i < dgv.Columns.Count; i++)
                    {
                        csv.WriteField(row.Cells[i].Value.ToString());
                    }
                    csv.NextRecord();
                }
            }
        }

    }


}
